import {
  _decorator,
  Component,
  Node,
  Sprite,
  UITransform,
  Animation,
  AnimationClip,
  animation,
  Vec3,
  SpriteFrame,
  debug,
} from 'cc'
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManage'
import ResourceManage from '../Runtime/resourceManage'
import {
  CONTROLLER_ENUM,
  DIRECTION_ENUM,
  DIRECTION_ORDER_ENUM,
  ENTITY_STATE_ENUM,
  ENTITY_TYPE_ENUM,
  EVENT_ENUM,
  PARAMS_NAME_ENUM,
} from '../Enums'
import EventManage from '../Runtime/eventManage'
import { IEntity } from '../Levels'
import { PlayerStateMachine } from '../Player/PlayerStateMachine'
import { randomByLen } from '../Utils'
const { ccclass, property } = _decorator

@ccclass('EntityManage')
export class EntityManage extends Component {
  id: string = randomByLen(12)
  x: number = 0
  y: number = 0
  fsm: PlayerStateMachine

  private _direction: DIRECTION_ENUM
  private _state: ENTITY_STATE_ENUM

  private type: ENTITY_TYPE_ENUM

  get direction() {
    return this._direction
  }

  set direction(newDirection: DIRECTION_ENUM) {
    this._direction = newDirection
    this.fsm.setParams(PARAMS_NAME_ENUM.DIRECTION, DIRECTION_ORDER_ENUM[this._direction])
  }

  get state() {
    return this._state
  }

  set state(newState: ENTITY_STATE_ENUM) {
    this._state = newState
    this.fsm?.setParams(this._state, true)
  }

  async init(params: IEntity) {
    const sprite = this.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM

    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4)

    this.x = params.x
    this.y = params.y
    this.type = params.type
    // 设置初始方向
    this.direction = params.direction
    // 通过设置参数来执行初始动画
    this.state = params.state
  }

  onDestroy() {}

  protected update(dt: number): void {
    this.node.setPosition(this.x * TILE_WIDTH - 1.5 * TILE_WIDTH, -this.y * TILE_HEIGHT + 1.5 * TILE_HEIGHT)
  }
}
